//
//  XMScreenLockController.m
//  XMScreenLockDemo
//
//  Created by sfk-ios on 2018/1/5.
//  Copyright © 2018年 sfk-JasonSu. All rights reserved.
//

#import "XMScreenLockController.h"

@interface XMScreenLockController ()

@property (weak, nonatomic) IBOutlet UILabel *tipsL;
@property (weak, nonatomic) IBOutlet UILabel *showPwdL;
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
@property (weak, nonatomic) IBOutlet UIView *numbersView;

@property (weak, nonatomic) IBOutlet UIButton *no1Btn;
@property (weak, nonatomic) IBOutlet UIButton *no2Btn;
@property (weak, nonatomic) IBOutlet UIButton *no3Btn;
@property (weak, nonatomic) IBOutlet UIButton *no4Btn;
@property (weak, nonatomic) IBOutlet UIButton *no5Btn;
@property (weak, nonatomic) IBOutlet UIButton *no6Btn;
@property (weak, nonatomic) IBOutlet UIButton *no7Btn;
@property (weak, nonatomic) IBOutlet UIButton *no8Btn;
@property (weak, nonatomic) IBOutlet UIButton *no9Btn;
@property (weak, nonatomic) IBOutlet UIButton *no0Btn;
/// 模糊背景
@property (weak, nonatomic) UIToolbar *toolBar;
/// 当前输入的密码字符组
@property (strong, nonatomic) NSMutableArray *currentInputArray;
/// 当前输入的密码
@property (copy, nonatomic) NSString *currentInputPwd;
/// 已输错的次数
@property (assign, nonatomic) int errorCount;

@end

@implementation XMScreenLockController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor blackColor];
    
    _errorCount = 0;
    [self setupBtn:_no0Btn];
    [self setupBtn:_no1Btn];
    [self setupBtn:_no2Btn];
    [self setupBtn:_no3Btn];
    [self setupBtn:_no4Btn];
    [self setupBtn:_no5Btn];
    [self setupBtn:_no6Btn];
    [self setupBtn:_no7Btn];
    [self setupBtn:_no8Btn];
    [self setupBtn:_no9Btn];
    
    self.currentInputPwd = @"○ ○ ○ ○";
    self.currentInputArray = [NSMutableArray array];
    self.showPwdL.text = _currentInputPwd;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:self.view.window.frame];
        imgView.image = [UIImage imageNamed:@"winterGIRL.jpg"];
        [self.view addSubview:imgView];
        
        UIToolbar *bar = [[UIToolbar alloc]initWithFrame:self.view.window.frame];
        bar.barStyle = UIBarStyleBlack;
        bar.userInteractionEnabled = YES;
        [self.view addSubview:bar];
        _toolBar = bar;
        
        [self.view sendSubviewToBack:bar];
        [self.view sendSubviewToBack:imgView];
        
    });

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

/// 忘记密码
- (IBAction)forgetBtnClick {
    NSLog(@"忘记密码");
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"是否重置密码为1234?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 保存密码到本地
        [[NSUserDefaults standardUserDefaults] setObject:@"1234" forKey:PWD_KEY];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前密码：1234" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];
    [alertVc addAction:cancel];
    [alertVc addAction:sure];
    
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (IBAction)deleteBtnClick {
    NSLog(@"删除");
    NSString *title = _deleteBtn.titleLabel.text;
    if ([title isEqualToString:@"删除"]) {
        [self updateInputStateWithNum:nil];
        return;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)no1BtnClick:(id)sender {
    NSLog(@"输入1");
    [self updateInputStateWithNum:@"1"];
}

- (IBAction)no2BtnClick:(id)sender {
    NSLog(@"输入2");
    [self updateInputStateWithNum:@"2"];
}

- (IBAction)no3BtnClick:(id)sender {
    NSLog(@"输入3");
    [self updateInputStateWithNum:@"3"];
}

- (IBAction)no4BtnClick:(id)sender {
    NSLog(@"输入4");
    [self updateInputStateWithNum:@"4"];
}

- (IBAction)no5BtnClick:(id)sender {
    NSLog(@"输入5");
    [self updateInputStateWithNum:@"5"];
}

- (IBAction)no6BtnClick:(id)sender {
    NSLog(@"输入6");
    [self updateInputStateWithNum:@"6"];
}

- (IBAction)no7BtnClick:(id)sender {
    NSLog(@"输入7");
    [self updateInputStateWithNum:@"7"];
}

- (IBAction)no8BtnClick:(id)sender {
    NSLog(@"输入8");
    [self updateInputStateWithNum:@"8"];
}

- (IBAction)no9BtnClick:(id)sender {
    NSLog(@"输入9");
    [self updateInputStateWithNum:@"9"];
}

- (IBAction)no0BtnClick:(id)sender {
    NSLog(@"输入0");
    [self updateInputStateWithNum:@"0"];
}

#pragma mark - other
/// 初始化按钮
- (void)setupBtn:(UIButton *)btn
{
    btn.layer.borderColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5].CGColor;
    btn.layer.cornerRadius = btn.frame.size.width *0.5;
    btn.layer.borderWidth = 1;
    btn.layer.masksToBounds = YES;
}

/// 更新输入状态
- (void)updateInputStateWithNum:(NSString *)numString
{
    if (!numString) {  // 删除
        [self.currentInputArray removeLastObject];
    }else {
        [self.currentInputArray addObject:numString];
    }
    
    if (self.currentInputArray.count == 4) {
        _currentInputPwd = @"● ● ● ●";
        _showPwdL.text = _currentInputPwd;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self checkPwd];
        });
    }else {
        
        [_deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
        switch (self.currentInputArray.count) {
            case 1:
            {
                _currentInputPwd = @"● ○ ○ ○";
                _showPwdL.text = _currentInputPwd;
            }
                break;
                
            case 2:
            {
                _currentInputPwd = @"● ● ○ ○";
                _showPwdL.text = _currentInputPwd;
            }
                break;
                
            case 3:
            {
                _currentInputPwd = @"● ● ● ○";
                _showPwdL.text = _currentInputPwd;
            }
                break;
                
            default:{
                _currentInputPwd = @"○ ○ ○ ○";
                _showPwdL.text = _currentInputPwd;
                [_deleteBtn setTitle:@"取消" forState:UIControlStateNormal];
            }
                break;
        }
        
    }
}

/// 验证输入的密码是否正确
- (void)checkPwd
{
    NSString *nowInputPwd = @"";
    for (NSString *word in self.currentInputArray) {
       nowInputPwd = [nowInputPwd stringByAppendingString:word];
    }
    NSLog(@"nowInputPwd==%@",nowInputPwd);
    
    NSString *myPwd = [[NSUserDefaults standardUserDefaults]objectForKey:PWD_KEY];
    if ([nowInputPwd isEqualToString:myPwd.length?myPwd:@"1234"]) {
        _tipsL.text = @"  密码正确 ^_^";
        _errorCount = 0;
        [self.currentInputArray removeAllObjects];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    }else {
        _tipsL.text = @"  密码错误！";
        [self.currentInputArray removeAllObjects];
        _currentInputPwd = @"○ ○ ○ ○";
        _showPwdL.text = _currentInputPwd;
        [self shakePwdL];
        _errorCount ++;
        if (_errorCount>=5) {
            _numbersView.userInteractionEnabled = NO;
            _tipsL.text = @"您已输错5次！请稍后再试";
            [_deleteBtn setTitle:@"取消" forState:UIControlStateNormal];
            return;
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _tipsL.text = @"请输入密码";
            [_deleteBtn setTitle:@"取消" forState:UIControlStateNormal];
        });
    }
}

/// 摇动动画
- (void)shakePwdL
{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: 0.3 ];
    rotationAnimation.duration = 0.1;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 3;
    rotationAnimation.removedOnCompletion = YES;
    // 结束后逆向执行
    rotationAnimation.autoreverses = YES;
    
    [self.showPwdL.layer addAnimation:rotationAnimation forKey:@"animateLayer"];
}

@end













